package com.hzhr.iot.web.controller;

import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.model.collectData.CollectDataGetModel;
import com.hzhr.iot.device.sdk.model.collectData.CollectDataModel;
import com.hzhr.iot.device.sdk.service.Device_CollectDataService;
import com.hzhr.iot.web.constant.DeviceOptions;
import com.hzhr.iot.web.controller.base.BaseController;
import com.hzhr.iot.web.model.response.BaseResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RequestMapping("/collectdata")
@Api(description = "采集数据")
@RestController
public class CollectDataController extends BaseController {
    @Autowired
    Device_CollectDataService device_collectDataService;

    @Autowired
    DeviceOptions deviceOptions;

    @ApiOperation(value = "采集数据", notes = "采集数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码",required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "单页面条数", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "collectdeviceId", value = "采集设备编号ID", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "begintime", value = "开始时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "endtime", value = "结束时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "iotdeviceId", value = "物联网设备ID", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "alarmstatus", value = "报警状态,207采集设备查询报警信息是用到", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "timetype", value = "查询时间周期,1.7天内数据", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "alarmstatustype", value = "报警状态比较类型查询.配合alarmstatus 1.等于 2.大于 3.小于 4.不等于", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "grouptype", value = "分组类型 1.时间分组", dataType = "int", required = false, paramType = "query")
    })
    @RequestMapping(value = "/getcollectdata", method = RequestMethod.POST)
    BaseResponse getcollectdata(@RequestParam(value ="pageNum", required = false) Integer pageNum,
                                @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                @RequestParam(value = "uat", required = true) String uat,
                                @RequestParam(value = "collectdeviceId", required = false) String collectdeviceId,
                                @RequestParam(value = "begintime", required = false) String begintime,
                                @RequestParam(value = "endtime", required = false) String endtime,
                                @RequestParam(value = "iotdeviceId", required = false) String iotdeviceId,
                                @RequestParam(value = "alarmstatus", required = false) Integer alarmstatus,
                                @RequestParam(value = "timetype", required = false) Integer timetype,
                                @RequestParam(value = "alarmstatustype", required = false) Integer alarmstatustype,
                                @RequestParam(value = "grouptype", required = false) Integer grouptype) throws Exception {
        Map<String, Object> result = new HashMap<>();

        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        if (!StringUtils.isEmpty(collectdeviceId)) {
            query.put("equal_collectDeviceId", collectdeviceId);
        }
        if (!StringUtils.isEmpty(iotdeviceId)) {
            query.put("equal_iotDeviceId", iotdeviceId);
        }
        if (!StringUtils.isEmpty(begintime)) {
            query.put("greaterthanorequal_currentTm", HzhrDateUtil.strToDate(begintime).getTime());
        }
        if (!StringUtils.isEmpty(endtime)) {
            query.put("lessthan_currentTm", HzhrDateUtil.strToDate(endtime).getTime());
        }
        if (alarmstatustype != null) {
            if (alarmstatustype == 4) {
                query.put("isnull_alarmCodes", false);
            }
        }
        query.put("show", "list");
        query.put("show_info", true);
        query.put("show_total", true);
        query.put("show_ext", true);
        query.put("orderBy_currentTm", "desc");
        query.put("page", pageNum);
        query.put("count", pageSize);
        CollectDataGetModel collectDataGetModel = device_collectDataService.get(header, query);
        List<CollectDataModel> collectDataModels = collectDataGetModel.getModelList();
        int total = collectDataGetModel.getTotal();

        List<Map<String, Object>> dataList = new ArrayList<>();
        for (CollectDataModel collectDataModel :
                collectDataModels) {
            Map<String, Object> data = new HashMap<>();
            data.put("currenttime", HzhrTypeUtil.object2string(collectDataModel.getCurrentTm()));
            Double currentvalue = collectDataModel.getCurrentValue();
            data.put("currentvalue",  currentvalue != null ? new BigDecimal(currentvalue).setScale(3, BigDecimal.ROUND_DOWN).toString() : null);
            data.put("cellvoltage",  HzhrTypeUtil.object2string(collectDataModel.getCellVoltage()));
            Double freezingvalue = collectDataModel.getFreezingValue();
            data.put("freezingvalue",  freezingvalue != null ? new BigDecimal(freezingvalue).setScale(3, BigDecimal.ROUND_DOWN).toString() : null);
            Double statotalflow = collectDataModel.getStaTotalFlow();
            data.put("statotalflow",  statotalflow != null ? new BigDecimal(statotalflow).setScale(3, BigDecimal.ROUND_DOWN).toString() : null);
            Double worktotalflow = collectDataModel.getWorkTotalFlow();
            data.put("worktotalflow",  worktotalflow != null ? new BigDecimal(worktotalflow).setScale(3, BigDecimal.ROUND_DOWN).toString() : null);
            data.put("disttotalflow",  HzhrTypeUtil.object2string(collectDataModel.getDisTotalFlow()));
            data.put("staflowrate",  HzhrTypeUtil.object2string(collectDataModel.getStaFlowRate()));
            data.put("workflowrate",  HzhrTypeUtil.object2string(collectDataModel.getWorkFlowRate()));
            data.put("temperature",  HzhrTypeUtil.object2string(collectDataModel.getTemperature()));
            data.put("pressure",  HzhrTypeUtil.object2string(collectDataModel.getPressure()));
            data.put("signalstrength",  HzhrTypeUtil.object2string(collectDataModel.getSignalStrength()));
            data.put("rsrq",  HzhrTypeUtil.object2string(collectDataModel.getSignalStrength()));

            Long freezingTime = collectDataModel.getFreezingTime();
            if (freezingTime != null) {
                data.put("freezingtime", HzhrDateUtil.dateToStr(new Date(freezingTime), "yyyy-MM-dd HH:mm:ss"));
            }

            Map<String, Object> options_valvestatus = new HashMap<>();
            options_valvestatus.put("name", collectDataModel.getValveStatusDes());
            data.put("options_valvestatus", options_valvestatus);

            Map<String, Object> options_alarmstatus = new HashMap<>();
            String alarmCodes = collectDataModel.getAlarmCodes();
            if (!StringUtils.isEmpty(alarmCodes)) {
                List<String> alarmCodesList = Arrays.asList(alarmCodes.toString().split(","));
                String alarmStatusName = "";
                for (int i = 0; i < alarmCodesList.size(); i++) {
                    String alarmCodesItem = alarmCodesList.get(i);
                    String alarmStatusNameItem = deviceOptions.getDesByCode("ALARM_TYPE", alarmCodesItem);
                    if (!StringUtils.isEmpty(alarmStatusNameItem)) {
                        if (i == alarmCodesList.size() - 1) {
                            alarmStatusName += alarmStatusNameItem;
                        } else {
                            alarmStatusName += alarmStatusNameItem + ", ";
                        }
                    }
                }
                options_alarmstatus.put("name", alarmStatusName);
            } else {
                options_alarmstatus.put("name", "正常");
            }
            data.put("options_alarmstatus", options_alarmstatus);

            dataList.add(data);
        }
        result.put("dataList", dataList);
        result.put("total", total);

        return new BaseResponse("0", "成功",result);

    }
}
